package com.mfnote.view.write;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Video.Thumbnails;
import android.provider.MediaStore.Video.VideoColumns;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.mfnote.adapter.BgImageAdaper;
import com.mfnote.adapter.ImagesListAdapter;
import com.mfnote.adapter.MyViewFactory;
import com.mfnote.adapter.VideoListAdapter;
import com.mfnote.db.dao.RemindDao;
import com.mfnote.db.dao.WriteDao;
import com.mfnote.model.RemindEntity;
import com.mfnote.model.WriteEntity;
import com.mfnote.util.ListTool;
import com.mfnote.util.MyReceiver;
import com.mfnote.util.RandomUtils;
import com.mfnote.util.ShareUtil;
import com.mfnote.util.image.ImageManager;
import com.mfnote.view.R;
import com.mfnote.view.chatemoji.ChatEmoji;
import com.mfnote.view.chatemoji.FaceAdapter;
import com.mfnote.view.chatemoji.FaceConversionUtil;
import com.mfnote.view.chatemoji.ViewPageAdapter;
import com.mfnote.view.other.MyApplication;

/**
 * 新建或详情或编辑记事本界面
 * 
 * @author ZHF
 * 
 */
public class NewWriteActivity extends Activity implements OnClickListener,
		OnItemClickListener {

	private static final int PHOTO_WITH_DATA = 18; // 从SD卡中得到图片
	private static final int PHOTO_WITH_CAMERA = 37;// 拍摄照片

	private static final int BACK_NONE = 1; // 定义Back键处理事件
	private static final int BACK_SAVE = 2;

	GridView gv_buttom_menu = null;
	EditText et_title_name;
	WriteEditText et_content; // 自定义编辑框
	TextView tv_titlebar_title;
	Button newwrite_titlebar_btn;
	AlertDialog alertDlgExit; // 提示保存对话框
	AlertDialog alertDlgRemind; // 内容提醒对话框
	ScrollView newwrite_scrollView;

	// 背景插入
	Gallery gallery = null;
	ImageSwitcher imageSwitcher = null;
	private int bgimagePos = 0;// 初始位置
	LinearLayout newwrite_ll_content;
	private int savebgId = 2130837517; // 需要保存的图片位置(默认为长颈鹿图片)
	private ListView newwrite_lv_image; // 图片所在的listView
	private AlertDialog alertDlgIsDel;
	
	public int[] bgImages = { R.drawable.background1, R.drawable.background2,
			R.drawable.background3, R.drawable.background4,
			R.drawable.background5, R.drawable.background6,
			R.drawable.background7, R.drawable.background8,
			R.drawable.background9, R.drawable.background10,
			R.drawable.background11, R.drawable.background12,
			R.drawable.background13, R.drawable.background14 };

	HashMap<String, Object> map = null; // 接收从WriteActivity传过来点击的是哪一项的所有数据
	boolean isEdit = false; // 是否可以编辑
	boolean isUpdate = false; // 标识它是否是编辑后更新保存
	boolean isDetails = false; // 标示是否是详情界面
	boolean isUpdateImage = false;// 标识是否是第二次插入图片

	// 选色框
	LinearLayout newwrite_ll_color = null;
	ImageButton btn_blue, btn_green, btn_pink, btn_red, btn_purple, btn_black;
	int textColor = -16777216;// 编辑框文字颜色

	// 插入图片
	ImageView newwrite_et_content_image;
	private String imgPath = ""; // 图片文件的路径
	private String imgName = ""; // 图片的名字
	private StringBuffer imagesPathBuf = new StringBuffer("");; // 保存所有插入图片的路径
	ImagesListAdapter adapter; // 自定义适配器
	static String tempStr = ""; // 用于保存传来图片路径
	// 视频保存路径

	// 切割字符串保存到集合中
	public static ArrayList<String> imgsList = null;
	// 第一次进入后，是否想继续添加图片
	boolean isContinued = false;
	public String tempdel = ""; // 接收删除图片时的路径
	public static int imgIndex; // 标示插入的是第几张图片，方便以后查找

	// 插入表情
	private View viewface_include; // 表情区域最外面
	private View viewface; // 表情区域
	private ViewPager vp_face; // 显示表情页的viewpager
	private ArrayList<View> pageViews; // 表情页界面集合
	private LinearLayout layout_point; // 游标显示布局
	private ArrayList<ImageView> pointViews; // 游标点集合
	private List<List<ChatEmoji>> emojis; // 表情集合
	private List<FaceAdapter> faceAdapters; // 表情数据填充器
	private int current = 0; // 当前表情页
	/** 表情页的监听事件 */
	private OnCorpusSelectedListener mListener;

	// 时间
	private String timeNow;// 系统当前时间

	// 用于保存这个界面原先的数据，用于后面保存的判断
	private String oldstrName; // 文件的旧名称
	private String oldcontent = "oldcontent"; // 文件的内容
	private String oldcolor; // 文件的旧名称
	private int oldbackground; // 文件的旧名称
	private String oldimagePath; // 文件的旧名称
	private String oldvideoPath = "";

	private boolean isChanged = true; // 整个界面数据发生变化

	// 内容提醒
	boolean isRemaind = false; // 输入的内容有提醒内容
	public static String keywords = ""; // 保存关键字
	boolean isRSuccess = false; // 是否提醒成功
	boolean remaind = false; // 插入数据库之前判断一下,是否有需要加提醒的内容
	Calendar calendar; // 日历获取时间

	PopupWindow mPopupWindow = null;// 弹出对话框
	LinearLayout newwrite_more_ll_share, newwrite_more_ll_bgselecter,
			newwrite_more_ll_accessory, newwrite_more_ll_ciku,newwrite_more_ll_video; // 弹出框中的分享和更换背景,附件

	// 提醒库DAO
	private RemindDao remindDao = null;

	// 识别出的关键字
	private List<String> keywordsList = new ArrayList<String>();

	// 时间值
	private List<HashMap<String, Object>> timeList = new ArrayList<HashMap<String, Object>>();
	// 获取手动提醒是点击的条目的position
	private int timerPosition = -1;

	private TextView tv_remind_time;

	private List<HashMap<String, Object>> list = null;

	// 提醒保存的title
	private String remindTitle;
    
	//视频列表
	private ListView newwrite_lv_video = null;
	//录制视频的返回值
	private static final int CAMERA_TRANSCRIBE = 1;
	//播放视频的返回值
	private static final int CAMERA_PLAY_VIDEO = 2;
	//视频缩略图
	private Bitmap bitmap = null;
	//保存所有图片的路径
	private List<String> videoList = new ArrayList<String>();
	
	private VideoListAdapter  videoAdapter = null;
	//所有视频的缩略图的path
	private StringBuffer videoStrings = new StringBuffer();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newwrite);

		MyApplication.getInstance().addActivity(this);

		// 加载底部控件
		loadButtomMenu();

		// 调用工具类，初始化表情集合
		FaceConversionUtil.getInstance().getFileText(NewWriteActivity.this);
		emojis = FaceConversionUtil.getInstance().emojiLists;

		newwrite_ll_content = (LinearLayout) findViewById(R.id.newwrite_ll_content);
		et_title_name = (EditText) findViewById(R.id.newwrite_et_title_name);
		tv_titlebar_title = (TextView) findViewById(R.id.newwrite_titlebar_title);
		newwrite_scrollView = (ScrollView) findViewById(R.id.newwrite_scrollView);

		// 创建自定义EditText
		et_content = new WriteEditText(NewWriteActivity.this);
		// 设置属性值
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		et_content.setLayoutParams(params);
		et_content.setBackgroundDrawable(null);
		et_content.setHint("随便记点事情吧。。。(插入图片在下部哦)");
		et_content.setSingleLine(false);
		et_content.setGravity(Gravity.TOP | Gravity.LEFT);
		// 绑定监听器
		// et_content.addTextChangedListener(new mTextWatcher());
		newwrite_ll_content.addView(et_content); // 将自定义的EditText加入到布局当中

		et_content.setOnClickListener(this);
		newwrite_lv_image = (ListView) findViewById(R.id.newwrite_lv_image);
		newwrite_lv_video = (ListView) findViewById(R.id.newwrite_lv_video);
		
		// 绑定监听器
		newwrite_lv_image.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击某一项弹出对话框，就对应显示其放大图
				String itemPath = (String) parent.getItemAtPosition(position);
				loadBigPictureDialog(itemPath);
			}
		});
		// 绑定长按删除监听器
		newwrite_lv_image
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						// 点击某一项弹出删除对话框
						tempdel = (String) parent.getItemAtPosition(position);
						loadDelPictureDialog();
						return false;
					}
				});
		
		// 绑定长按删除视频监听器
		newwrite_lv_video
		.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent,
					View view, int position, long id) {
				// 点击某一项弹出删除对话框
				loadDelVideoDialog(position);
				return false;
			}
		});
		
		//播放当前视频文件
		newwrite_lv_video.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String bitmapName = videoList.get(position);
				String mp4Name = bitmapName.substring(0, bitmapName.length()-4)+".mp4";
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse("/mnt/sdcard/MFNote/notes/"+mp4Name),
						"video/mp4");
				startActivityForResult(intent, CAMERA_PLAY_VIDEO);
			}
			
		});
		

		// 显示图片
		// newwrite_et_content_image = (ImageView)
		// findViewById(R.id.newwrite_et_content_image);
		// newwrite_et_content_image.setOnClickListener(this);
		// 选色条
		newwrite_ll_color = (LinearLayout) findViewById(R.id.newwrite_ll_color);
		// 加载选色按钮
		btn_blue = (ImageButton) findViewById(R.id.color_blue);
		btn_green = (ImageButton) findViewById(R.id.color_green);
		btn_pink = (ImageButton) findViewById(R.id.color_pink);
		btn_red = (ImageButton) findViewById(R.id.color_red);
		btn_purple = (ImageButton) findViewById(R.id.color_purple);
		btn_black = (ImageButton) findViewById(R.id.color_black);
		// 绑定监听器
		btn_blue.setOnClickListener(this);
		btn_green.setOnClickListener(this);
		btn_pink.setOnClickListener(this);
		btn_red.setOnClickListener(this);
		btn_purple.setOnClickListener(this);
		btn_black.setOnClickListener(this);

		// 点击listView列表后获取该项的数据并传递过来（title、content、backgrond、当然还有重要的imagePath）
		Intent intent = getIntent();
		map = (HashMap<String, Object>) intent.getSerializableExtra("map");
		// isEdit = (Boolean) intent.getSerializableExtra("isEdit");
		if (intent.getSerializableExtra("isEdit") != null) {
			isEdit = (Boolean) intent.getSerializableExtra("isEdit");
		}
		if (map != null) { // 详情
			loadWriteDetail();
			isUpdate = true;
		}

		remindDao = new RemindDao(this);
	}
	
	/**删除当前视频**/
	private void loadDelVideoDialog(final int position){
		// 对传入的item的map进行剖析处理
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_isdelete, null);
		alertDlgIsDel= new AlertDialog.Builder(this).create();
		alertDlgIsDel.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgIsDel.setContentView(viewDialog, layoutParams);
		Button btn_delete_sure=(Button) viewDialog.findViewById(R.id.btn_delete_sure);
		Button btn_delete_cancel=(Button) viewDialog.findViewById(R.id.btn_delete_cancel);
		btn_delete_sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//TODO 删除
				videoList.remove(position);
				if(videoList.size()>=0){
					videoAdapter = new VideoListAdapter(NewWriteActivity.this,videoList);
					newwrite_lv_video.setAdapter(videoAdapter); 
					ListTool.setListViewHeightBasedOnChildren(newwrite_lv_video);
				}
				alertDlgIsDel.dismiss();
			}
		});
		btn_delete_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgIsDel.dismiss();
			}
		});
	} 

	/** 加载详情 **/
	private void loadWriteDetail() {
		// Toast.makeText(NewWriteActivity.this, "点击左上角按钮，进行编辑",
		// Toast.LENGTH_LONG).show();
		if (!isEdit) {
			// 不能进行编辑
			et_title_name.setEnabled(false);
			et_content.setEnabled(false);
			gv_buttom_menu.setEnabled(false);
			newwrite_lv_image.setEnabled(false);
		}
		// 加载数据
		et_title_name.setText(map.get("title").toString()); // 标题
		// et_content = new WriteEditText(NewWriteActivity.this,
		// map.get("content").toString(),emojis);
		// et_content.setText(map.get("content").toString()); //内容
		// 将获取的内容字符串中[笑脸]转换成图片
		et_content.insetBitmap(map.get("content").toString(),
				map.get("imagePath").toString());

		et_content.setTextColor(Integer.parseInt(map.get("color").toString())); // 颜色

		newwrite_scrollView.setBackgroundResource(Integer.parseInt(map.get(
				"background").toString())); // 背景

		isDetails = true; // 用于标示后面图片的来源

		oldstrName = map.get("title").toString();// 记下打开文件的名称
		oldcontent = map.get("content").toString();
		oldcolor = map.get("color").toString();
		oldbackground = (Integer) map.get("background");
		oldimagePath = map.get("imagePath").toString();
		oldvideoPath = map.get("videoPath").toString();

		if (!map.get("imagePath").equals("")) {
			loadPictureAdapter();// 加载图片列表数据
		}
		
		if(!map.get("videoPath").equals("")){
			//加载视频列表数据
			String videoPath = map.get("videoPath").toString();
			videoList = new ImageManager(this).str2List(videoPath);
			loadVideoAdapter(videoList);
		}
		// 视频加载位置

		// 更换titleBar,添加编辑按钮事件
		tv_titlebar_title.setText("");
		newwrite_titlebar_btn = (Button) findViewById(R.id.newwrite_titlebar_btn);
		newwrite_titlebar_btn.setVisibility(View.VISIBLE);
		newwrite_titlebar_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				et_title_name.setEnabled(true);
				et_content.setEnabled(true);
				gv_buttom_menu.setEnabled(true);
				newwrite_lv_image.setEnabled(true);
				Toast.makeText(NewWriteActivity.this, "现在可以进行编辑了！",
						Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	/** 加载视频列表适配器(显示的是视频的缩略图) **/
	private void loadVideoAdapter(List<String> videoPath){
		videoAdapter = new VideoListAdapter(this, videoPath);
		newwrite_lv_video.setAdapter(videoAdapter);
		ListTool.setListViewHeightBasedOnChildren(newwrite_lv_video);
	}

	/** 加载图片列表适配器 **/
	private void loadPictureAdapter() {

		if (isDetails) { // 进入详情界面加载图片列表
			tempStr = map.get("imagePath").toString();// 点击某一项后从数据库获取数据后，传到此界面
			isUpdateImage = true;
		} else {
			if (isUpdateImage) {// 进入详情后继续插入图片
				tempStr = tempStr + imagesPathBuf.toString();
				isContinued = true;
			} else {
				// 可能没有添加完，再次插入图片
				tempStr = imagesPathBuf.toString(); // 接收刚刚多次拍完照后记录下的多条照片的路径集
			}
		}
		// 切割插入图片路径字符串保存到集合中
		imgsList = new ImageManager(this).str2List(tempStr);
		adapter = new ImagesListAdapter(NewWriteActivity.this, imgsList);
		newwrite_lv_image.setAdapter(adapter);
		// 调用此方法解决ScrollView中包含ListView只能显示两行的弊端
		ListTool.setListViewHeightBasedOnChildren(newwrite_lv_image);
	}

	/** 加载底部菜单布局 **/
	private void loadButtomMenu() {
		gv_buttom_menu = (GridView) this
				.findViewById(R.id.newwrite_gv_buttom_menu);
		gv_buttom_menu.setSelector(new ColorDrawable(Color.TRANSPARENT)); // 去掉自身自带的按下背景效果

		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = null;

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.newwrite_menu_color);
		map.put("itemText", "颜色");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.newwrite_menu_face);
		map.put("itemText", "表情");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.remind);
		map.put("itemText", "提醒");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.save);
		map.put("itemText", "保存");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.more);
		map.put("itemText", "更多");
		data.add(map);

		SimpleAdapter adapter = new SimpleAdapter(this, data,
				R.layout.buttom_menu_item, new String[] { "itemImage",
						"itemText" }, new int[] { R.id.item_image,
						R.id.item_text });
		gv_buttom_menu.setAdapter(adapter);

		gv_buttom_menu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0: { // 颜色
					// 显示选色框
					if (newwrite_ll_color.getVisibility() == View.GONE) {
						newwrite_ll_color.setVisibility(View.VISIBLE);
					} else {
						newwrite_ll_color.setVisibility(View.GONE);
						;
					}
					break;
				}
				case 1: {// 插入
					// 初始化插入表情(控件，数据)
					initFace();
					// 弹出底部表情选择对话框
					viewface_include = findViewById(R.id.face_include);
					if (viewface_include.getVisibility() == View.VISIBLE) {
						viewface_include.setVisibility(View.GONE);
					} else {
						viewface_include.setVisibility(View.VISIBLE);
					}
					break;
				}
				case 2: {// 提醒
					// 闹钟提醒，生成快捷方式，再次点击进入生成快捷方式
					// 弹出时间选择框选择时间，开启服务，接收广播
					openTimerPickerDialog();
					break;
				}
				case 3: {// 保存
					saveorupdateWrite();
					break;
				}
				case 4: {// 更多
					// 此处改进成弹出右下角
					popupMoreWindow(view);
					break;
				}
				}
			}
		});
	}

	/** 保存文件或更新文件 **/
	private void saveorupdateWrite() {
		String strName = et_title_name.getText().toString(); // 文件名
		remindTitle = strName;
		String strContent = et_content.getText().toString(); // 文件内容
		String color = String.valueOf(textColor); // 字体颜色

		Date date = new Date(System.currentTimeMillis()); // 系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		timeNow = dateFormat.format(date); // 保存时的时间

		String saveimgPath = tempStr; // 保存插入的图片
		int saveBackGroundId = savebgId; // 背景图片索引
		// 视频路径
		StringBuffer savevideoPath = new StringBuffer();
		if(videoList.size()>0){
			for(int i=0;i<videoList.size();i++){
				savevideoPath.append(videoList.get(i));
			}
		}else{
			savevideoPath.append("");
		}
		

		String tempsaveBackGroundId = saveBackGroundId + "";
		// 如果整个界面的数据没有发生变，就不用进行数据库保存或者更新操作啦
		if (strName.equals(oldstrName) && strContent.equals(oldcontent)
				&& color.equals(oldcolor) && saveimgPath.equals(oldimagePath)
				&& tempsaveBackGroundId.equals(oldbackground + "")&&savevideoPath.toString().equals(oldvideoPath)) {
			isChanged = false;
		}

		if (isChanged) { // 界面数据发生变化
			// 判读是否为空
			if (strContent.equals("")) {
				Toast.makeText(NewWriteActivity.this, "文件内容不能为空",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行保存，如果文件名为空，用内容代替
				if (strName.equals("")) {
					strName = strContent;
					remindTitle = strName;
				}
				if (!strName.equals(oldstrName)) { // 名字不一样就是新的一条记录哦
					isUpdate = false;
				}

				// 插入数据库之前判断一下,是否有需要加提醒的内容
				boolean remaind = queryRemind(strContent);
				if (remaind == true) {
					System.out.println(keywords);
					// 此处弹出提醒对话框后，将获取到的内容设置成提醒，处理完成后再将其保存到数据库

					openRemaindDialog(); // 提醒对话框
					// isRSuccess = true;

				}
				if (isRSuccess == true || remaind == false) {
					saveorupdate(strName, strContent, color, saveimgPath,
							savevideoPath.toString(), saveBackGroundId);
				}
			}
		}
	}

	/** 仅仅是保存或更新操作没有前期判断 **/
	private void saveorupdate(String strName, String strContent, String color,
			String saveimgPath, String saveVideoPath, int saveBackGroundId) {
		if (!isUpdate) { // 新建一条记录再保存

			// 将这条记录插入数据库
			WriteEntity writeEntity = new WriteEntity(strName, strContent,
					saveimgPath, saveVideoPath, timeNow, color,
					saveBackGroundId, 0);
			// long state
			// =DBHelper.getInstance(NewWriteActivity.this).insertWrite(writeEntity);
			long state = new WriteDao(NewWriteActivity.this)
					.insertWrite(writeEntity);
			// 添加成功
			if (state != -1) {
				Toast.makeText(NewWriteActivity.this, "保存成功！",
						Toast.LENGTH_SHORT).show();
				// 跳转到列表界面
				Intent intent = new Intent(NewWriteActivity.this,
						WriteActivity.class);
				setResult(1);
				startActivity(intent);
				NewWriteActivity.this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			} else {
				Toast.makeText(NewWriteActivity.this, "保存失败！",
						Toast.LENGTH_SHORT).show();
			}
		} else { // 编辑后保存更新
			// 将这条记录更新到数据库
			WriteEntity writeEntity = new WriteEntity(strName, strContent,
					saveimgPath, saveVideoPath, timeNow, color,
					saveBackGroundId, 0);
			// long state
			// =DBHelper.getInstance(NewWriteActivity.this).updateWrite(writeEntity);
			long state = new WriteDao(NewWriteActivity.this)
					.updateWrite(writeEntity);
			// 更新成功
			if (state != -1) {
				Toast.makeText(NewWriteActivity.this, "更新成功！",
						Toast.LENGTH_SHORT).show();
				// 跳转到列表界面
				Intent intent = new Intent(NewWriteActivity.this,
						WriteActivity.class);
				setResult(1);
				startActivity(intent);
				NewWriteActivity.this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			} else {
				Toast.makeText(NewWriteActivity.this, "更新失败！",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	/** 弹出插入图片选择对话框 **/
	private void loadSelectPictureDialog() {
		// 自定义Context,添加主题
		Context dialogContext = new ContextThemeWrapper(NewWriteActivity.this,
				android.R.style.Theme_Light);
		String[] choiceItems = new String[2];
		choiceItems[0] = "相机拍摄"; // 拍照
		choiceItems[1] = "本地相册"; // 从相册中选择
		ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choiceItems);
		// 对话框建立在刚才定义好的上下文上
		AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle("添加图片");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0: // 相机
							doTakePhoto();
							break;
						case 1: // 从图库相册中选取
							// doPickPhotoFromGallery();
							Intent intent2 = doPickPhotoFromGallery();
							startActivityForResult(intent2, PHOTO_WITH_DATA);
							break;
						}
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/** 弹出放大的插入图片 **/
	public void loadBigPictureDialog(String itemPath) {

		final String temp = itemPath; // 用于接收传来的某一项的图片地址

		Dialog dialog_pic = new Dialog(NewWriteActivity.this,
				R.style.simple_dialog);

		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.from(NewWriteActivity.this).inflate(
				R.layout.newwrite_dialog_picture, null);

		ImageView imgView = (ImageView) view.findViewById(R.id.img_weibo_img);
		Button btnBig = (Button) view.findViewById(R.id.btn_big);
		btnBig.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewWriteActivity.this,
						ImgDisplayActivity.class);

				intent.putExtra("imgUrl", temp); // 将图片的路径传递过去
				startActivity(intent);
			}
		});
		dialog_pic.setContentView(view);
		dialog_pic.show();

		if (!itemPath.equals("")) {

			Bitmap tempBitmap = BitmapFactory.decodeFile(itemPath); // 加载对应项的地址

			imgView.setImageBitmap(tempBitmap);// 显示对应项的图片
		}
	}

	/** 弹出背景选择对话框 **/
	private void loadSelectBgDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("背景选择");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				newwrite_scrollView.setBackgroundResource(bgImages[bgimagePos
						% bgImages.length]);
				savebgId = bgImages[bgimagePos % bgImages.length]; // 将其保存起来
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.image_bg_switcher, null);

		gallery = (Gallery) view.findViewById(R.id.img_gallery);
		gallery.setAdapter(new BgImageAdaper(this, bgImages)); // 将内容的设置交给自定义的适配器
		gallery.setSelection(bgImages.length / 2); // 显示一个个长条（图片组）

		imageSwitcher = (ImageSwitcher) view.findViewById(R.id.img_switcher);
		imageSwitcher.setFactory(new MyViewFactory(this)); // 将imageSwitcher中的内容交给MyViewFactory来处理
		// 给Gallery添加响应事件
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				bgimagePos = position; // 保存选中的图片position
				imageSwitcher.setImageResource(bgImages[position
						% bgImages.length]);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		builder.setView(view);
		Dialog dialog = builder.create();

		dialog.show();

	}

	/** 删除图片对话框 **/
	private void loadDelPictureDialog() {
		// 对传入的item的map进行剖析处理
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_isdelete, null);
		alertDlgIsDel= new AlertDialog.Builder(this).create();
		alertDlgIsDel.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgIsDel.setContentView(viewDialog, layoutParams);
		Button btn_delete_sure=(Button) viewDialog.findViewById(R.id.btn_delete_sure);
		Button btn_delete_cancel=(Button) viewDialog.findViewById(R.id.btn_delete_cancel);
		btn_delete_sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 接收不同阶段的所有图片路径集合
				if (isDetails) { // 进入详情界面加载图片列表
					tempStr = map.get("imagePath").toString();// 点击某一项后从数据库获取数据后，传到此界面
					isUpdateImage = true;
				} else {
					if (isUpdateImage) {
						// 第一次进入后，想继续添加图片
						tempStr = tempStr + "";
					} else {
						// 可能没有添加完，再次插入图片
						tempStr = imagesPathBuf.toString(); // 接收刚刚多次拍完照后记录下的多条照片的路径集
					}
				}
				// 将所要删除的字符串从上面接受的字符中删除掉
				String tempNew = tempStr.replace(tempdel, "");
				StringBuffer imagesPathBuf2 = new StringBuffer("");
				tempStr = imagesPathBuf2.append(tempNew).toString(); // 重新将删除后的新图片路径加到里面去
				imagesPathBuf = imagesPathBuf2;  //将删除后的图片路径保存到当前
				isDetails = false; // 避免接着删除第二张图片时前面删过的又出来
				// 切割插入图片路径字符串保存到集合中
				imgsList = new ImageManager(NewWriteActivity.this)
						.str2List(tempStr);
				adapter = new ImagesListAdapter(NewWriteActivity.this, imgsList);
				newwrite_lv_image.setAdapter(adapter);
				// 调用此方法解决ScrollView中包含ListView只能显示两行的弊端
				ListTool.setListViewHeightBasedOnChildren(newwrite_lv_image);
				
				//这里还得要将数据库里的图片路径更新
				
				alertDlgIsDel.dismiss();
			}
		});
		btn_delete_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgIsDel.dismiss();
			}
		});
	}

	/** 提醒对话框 **/
	private void openRemaindDialog() {
		final Dialog builder = new Dialog(this, R.style.login_dialog_Dialog);

		builder.show();
		LayoutInflater inflater = LayoutInflater.from(this);
		View viewDialog = inflater.inflate(R.layout.dialog_newwrite_remain,
				null);
		Display display = this.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		// int height = display.getHeight();
		LayoutParams layoutParams = new LayoutParams(width * 90 / 100,
				LayoutParams.WRAP_CONTENT);
		builder.setContentView(viewDialog, layoutParams);

		final ListView lv = (ListView) viewDialog
				.findViewById(R.id.lv_shortcut_item);

		list = new ArrayList<HashMap<String, Object>>();
		list.clear();
		for (int i = 0; i < keywordsList.size(); i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", keywordsList.get(i));
			map.put("time", "单击设置提醒时间");
			map.put("checked", false);
			list.add(map);
		}

		SimpleAdapter adapter = new SimpleAdapter(this, list,
				R.layout.remind_item,
				new String[] { "name", "time", "checked" }, new int[] {
						R.id.tv_shortcut_text, R.id.tv_remind_time,
						R.id.cb_shortcut_check });
		lv.setAdapter(adapter);
		// lv.setAdapter(new RemindAdapter(NewWriteActivity.this, list));
		// lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// listItem.remove(position);
				CheckBox cb = (CheckBox) view
						.findViewById(R.id.cb_shortcut_check);
				tv_remind_time = (TextView) lv.getChildAt(position)
						.findViewById(R.id.tv_remind_time);
				timerPosition = position;
				if (cb.isChecked()) {
					cb.setChecked(false);
					tv_remind_time.setText("单击设置提醒时间");
				} else {
					cb.setChecked(true);
					openTimerChoiceDialog();
				}
			}

		});

		Button btn_sure = (Button) viewDialog.findViewById(R.id.sure_btn);
		Button btn_cancle = (Button) viewDialog.findViewById(R.id.cancel_btn);
		// TextView tv_remind_time = (TextView)
		// viewDialog.findViewById(R.id.tv_remind_time);

		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//生成所选项的提醒
				Intent intent = new Intent("com.mfnote.view");
				intent.setClass(NewWriteActivity.this, MyReceiver.class);

				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				// hashMap
				String strName = remindTitle;
				String strContent = et_content.getText().toString(); // 文件内容
				String color = String.valueOf(textColor); // 字体颜色
				String time = timeNow;
				String saveimgPath = tempStr; // 保存插入的图片
				int saveBackGroundId = savebgId; // 背景图片索引
				StringBuffer savevideoPath = new StringBuffer();
				if(videoList.size()>0){
					for(int i=0;i<videoList.size();i++){
						savevideoPath.append(videoList.get(i));
					}
				}else{
					savevideoPath.append("");
				}
				
				hashMap.put("title", strName);
				hashMap.put("content", strContent);
				hashMap.put("color", color);
				hashMap.put("time", time);
				hashMap.put("imagePath", saveimgPath);
				hashMap.put("videoPath", savevideoPath.toString());
				hashMap.put("background", saveBackGroundId);
				hashMap.put("lock", 0);
				intent.putExtra("map", hashMap);
				for (int i = 0; i < timeList.size(); i++) {
					Log.d("timeList", timeList.get(i).get("hour") + "---"
							+ timeList.get(i).get("minute"));
					int hour = (Integer) timeList.get(i).get("hour");
					int minute = (Integer) timeList.get(i).get("minute");
					AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
					Calendar ca = Calendar.getInstance();
					ca.set(Calendar.HOUR_OF_DAY, hour);
					ca.set(Calendar.MINUTE, minute);
					int requestCode = RandomUtils.getRequestCode();
					intent.putExtra("requestCode", requestCode);
					PendingIntent pi = PendingIntent.getBroadcast(
							NewWriteActivity.this, requestCode, intent, 0);
					// 获取AlarmManager对象
					am.set(AlarmManager.RTC_WAKEUP, ca.getTimeInMillis(), pi); // 时间到时，执行PendingIntent，只执行一次

				}
				isRSuccess = true;
				remaind = false;
				saveorupdate(strName, strContent, color, saveimgPath,
						savevideoPath.toString(), saveBackGroundId);
				builder.dismiss();

			}
		});

		btn_cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				builder.dismiss();
				String strName = remindTitle;
				String strContent = et_content.getText().toString(); // 文件内容
				String color = String.valueOf(textColor); // 字体颜色
				String saveimgPath = tempStr; // 保存插入的图片
				int saveBackGroundId = savebgId; // 背景图片索引
				StringBuffer savevideoPath = new StringBuffer();
				if(videoList.size()>0){
					for(int i=0;i<videoList.size();i++){
						savevideoPath.append(videoList.get(i));
					}
				}else{
					savevideoPath.append("");
				}
				saveorupdate(strName, strContent, color, saveimgPath,
						savevideoPath.toString(), saveBackGroundId);

			}
		});

		// AlertDialog.Builder builder = new
		// AlertDialog.Builder(NewWriteActivity.this)
		// .setTitle("提示")
		// .setMessage("检测到内容中有“ "+keywords+" ”是否为其加入时间提醒")
		// // 确认
		// .setPositiveButton("加入提醒", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// //处理提醒呗，现在有要提醒的内容 keywords
		// //弹出时间选择框选择时间，开启服务，接收广播
		// openTimerPickerDialog();
		// }
		// })
		// // 取消
		// .setNegativeButton("不了，谢谢", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// isRSuccess = true;
		// remaind = false;
		// saveorupdateWrite(); //调用一下保存到数据库
		// }
		// });
		// Dialog dialog = builder.create();
		// dialog.show();
	}

	/** 时间设置对话框 **/
	private void openTimerChoiceDialog() {
		calendar = Calendar.getInstance();
		int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);

		TimePickerDialog timePickerDialog = new TimePickerDialog(
				NewWriteActivity.this, new MyTimePickerHandDialog(), hourOfDay,
				minute, true);
		timePickerDialog.setTitle("设置要提醒的时间");
		timePickerDialog.show(); // 显示对话框
	}

	/** 定时时间选择对话框 **/
	private void openTimerPickerDialog() {
		// 1）获得AlarmManager实例：
		// AlarmManager对象一般不直接实例化，而是通过Context.getSystemService(Context.ALARM_SERVIECE)
		// 方法获得
		// 2）定义一个PendingIntent来发出广播。
		// 3）调用AlarmManager的相关方法，设置定时、重复提醒等功能。

		// 获取当前的时间
		calendar = Calendar.getInstance();
		int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);

		TimePickerDialog timePickerDialog = new TimePickerDialog(
				NewWriteActivity.this, new MyTimePickerDialog(), hourOfDay,
				minute, true);
		timePickerDialog.setTitle("设置要提醒的时间");
		timePickerDialog.show(); // 显示对话框
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) { // 返回成功

			ImageManager imgManager = new ImageManager(this);// 图片管理类
			switch (requestCode) {
			case PHOTO_WITH_CAMERA: {// 拍照获取图片
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) { // 是否有SD卡

					Bitmap bitmap = imgManager.bitmapfromFilePath(Environment
							.getExternalStorageDirectory() + "/image.jpg");

					imgName = imgManager.createFileName();// 为照片创建不同的名字
					// 保存到SD卡
					imgManager.savePhotoToSDCard(
							Environment.getExternalStorageDirectory()
									+ "/MFNote/notes", imgName, bitmap);
					// 文件完整路径
					imgPath = Environment.getExternalStorageDirectory()
							+ "/MFNote/notes/" + imgName; // 获取SD卡下的图片

					// 判断进入详情界面后又进行插入图片的操作
					if (isDetails) {
						isDetails = false;
					}
					if (isContinued) {
						imagesPathBuf = new StringBuffer("");
					}
					// 保存该所有图片的路径字符串，将其组合成一个大的字符串
					imagesPathBuf.append(imgPath);

					// 更新加载图片列表适配器
					loadPictureAdapter();

					Toast.makeText(NewWriteActivity.this,
							"已保存SD卡MFNote/notes文件夹下", Toast.LENGTH_SHORT)
							.show();

					// 拍完照后，在编辑框中留下特殊标记"[img" + imgIndex + "]",点击实现超链接
					et_content.setImage(imgPath);
					imgIndex++;
				} else {
					Toast.makeText(NewWriteActivity.this, "没有SD卡",
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
			case PHOTO_WITH_DATA: {// 从图库中选择图片
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) { // 是否有SD卡

					ContentResolver resolver = getContentResolver();
					// 照片的原始资源地址
					Uri originalUri = data.getData();
					try {
						// 使用ContentProvider通过URI获取原始图片
						// Bitmap photo =
						// MediaStore.Images.Media.getBitmap(resolver,
						// originalUri);
						Bitmap photo = data.getParcelableExtra("data"); //获取裁剪后的图片

						// 此处调用系统裁剪功能，并将图片裁剪后图片保存，之后在加载图片列表适配器中显示出来

						imgName = imgManager.createFileName();// 创建图片名称
						// 保存图片到SD卡
						imgManager.savePhotoToSDCard(
								Environment.getExternalStorageDirectory()
										+ "/MFNote/notes", imgName, photo);
						// //图片的完整路径
						imgPath = Environment.getExternalStorageDirectory()
								+ "/MFNote/notes/" + imgName;

						// 判断进入详情界面后又进行插入图片的操作
						if (isDetails) {
							isDetails = false;
						}
						if (isContinued) { // 详情除第一次添加图片的以后添加
							imagesPathBuf = new StringBuffer("");
						}
						// 保存该所有图片的路径字符串，将其组合成一个大的字符串
						imagesPathBuf.append(imgPath);
						// 更新加载图片列表适配器
						loadPictureAdapter();

					} catch (Exception e) {
						e.printStackTrace();
					}
					Toast.makeText(NewWriteActivity.this,
							"已保存SD卡MFNote/notes文件夹下", Toast.LENGTH_SHORT)
							.show();
					// 拍完照后，在编辑框中留下特殊标记"[img" + imgIndex + "]",点击实现超链接
					et_content.setImage(imgPath);
					imgIndex++;
				} else {
					Toast.makeText(NewWriteActivity.this, "没有SD卡",
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
			case CAMERA_TRANSCRIBE:
				//完成视频录制之后的处理
				// 文件写完之后删除/sdcard/dcim/CAMERA/XXX.MP4,并保存到/mnt/sdcard/MFNote/write/dc.mp4
				deleteDefaultFile(data.getData());
				
				break;
			case CAMERA_PLAY_VIDEO:
				//完成视频播放之后的处理
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/**创建图片的名称**/
	private String createBitmapName(){
		Date date = new Date(System.currentTimeMillis());  //系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String fileName = dateFormat.format(date);
		return fileName;
	}
	
	// 删除在/sdcard/dcim/Camera/默认生成的文件
	private void deleteDefaultFile(Uri uri) {
			String fileName = null;
			if (uri != null) {
				// content
				Log.d("Scheme", uri.getScheme().toString());
				if (uri.getScheme().toString().equals("content")) {
					Cursor cursor = this.getContentResolver().query(uri, null,
							null, null, null);
					if (cursor.moveToNext()) {
						int columnIndex = cursor
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
						fileName = cursor.getString(columnIndex);
						//获取缩略图id
						int id = cursor.getInt(cursor
								.getColumnIndex(VideoColumns._ID));
						//获取缩略图
						bitmap = Thumbnails.getThumbnail(
								getContentResolver(), id, Thumbnails.MICRO_KIND,
								null);
						Bitmap tembitmap = ImageManager.zoomBitmap(bitmap, bitmap.getWidth() * 2, bitmap.getHeight());
						
						bitmap = ImageManager.syntheticImages(NewWriteActivity.this, tembitmap);
						
						if (!fileName.startsWith("/mnt")) {
							fileName = "/mnt" + fileName;
						}
						Log.d("fileName", fileName);
					}
				}
			}
			
			File file = new File(fileName);
			if (file.exists()) {
				if(file.length()>1){
					//TODO 加载到newwrite_lv_video中
					//保存文件
					try {
						//保存音频文件
						String bitmapName = createBitmapName();
						AssetFileDescriptor videoAsset = getContentResolver()
								.openAssetFileDescriptor(uri, "r");
						FileInputStream fis = videoAsset.createInputStream();
						File tmpFile = new File(
								"/mnt/sdcard/MFNote/notes/",
								bitmapName+".mp4");
						FileOutputStream fos = new FileOutputStream(tmpFile);

						byte[] buf = new byte[1024];
						int len;
						while ((len = fis.read(buf)) > 0) {
							fos.write(buf, 0, len);
						}
						fis.close();
						fos.close();
						//保存图片
						FileOutputStream fos2 = new FileOutputStream(new File("/mnt/sdcard/MFNote/notes/"+bitmapName+".png"));
						bitmap.compress(CompressFormat.PNG, 50, fos2);
						fos2.flush();
						fos2.close();
						videoList.add(bitmapName+".png");
						Log.d("videoList", videoList.get(0));
						loadVideoAdapter(videoList);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				// 删除文件
				file.delete();
				Log.d("delete", "删除成功");
			}
		}

	/** 从相册获取图片 **/
	private Intent doPickPhotoFromGallery() {
		Intent intent = new Intent();
		intent.setType("image/*"); // 开启Pictures画面Type设定为image
		intent.setAction(Intent.ACTION_GET_CONTENT); // 使用Intent.ACTION_GET_CONTENT这个Action

		// 实现对图片的裁剪，必须要设置图片的属性和大小
		intent.setType("image/*"); // 获取任意图片类型
		intent.putExtra("crop", "true"); // 滑动选中图片区域
		intent.putExtra("aspectX", 1); // 裁剪框比例1:1
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300); // 输出图片大小
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true); // 有返回值

		return intent;

		// startActivityForResult(intent, PHOTO_WITH_DATA); //取得相片后返回到本画面
	}

	/** 拍照获取相片 **/
	private void doTakePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机

		Uri imageUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), "image.jpg"));
		// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

		// 直接使用，没有缩小
		startActivityForResult(intent, PHOTO_WITH_CAMERA); // 用户点击了从相机获取
	}

	/** 获取图库文件路径 **/
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/** 对文本内容进行查询数据库识别 **/
	public boolean queryRemind(String content) {
		// 首先扫描内容，获取关键字（数字、航班、闹钟）
		// 之后为其添加特殊属性（高亮显示，超链接）
		// 将该属性保存到数据库
		ArrayList<HashMap<String, Object>> listmap = remindDao.getAllReminds();
		String[] keyWords = new String[listmap.size()];
		for (int i = 0; i < keyWords.length; i++) {
			keyWords[i] = (String) listmap.get(i).get("name");
		}
		keywordsList.clear();
		getRemindString(content, keyWords);

		// StringBuffer digitBuf = new StringBuffer();
		// boolean isDigit = content.matches(".*\\d.*");
		// if(isDigit) { //里面包含数字
		// //获取该数字
		// for (int i = 0; i < content.length(); i++) {
		// boolean temp = Character.isDigit(content.charAt(i));
		// if(temp) {//是数字
		// //保存起来
		// digitBuf.append(content.charAt(i)); //将当前的这个数字保存起来
		// }
		// }
		// if(digitBuf.length() > 2) { //判断数字长度 至少3位
		// //对该数字进行高亮处理
		// isRemaind = true;
		// keywords = digitBuf.toString();
		// }
		// }
		// boolean isMetting = content.contains("会议");
		// boolean isFlight = content.contains("航班");
		// if(isMetting == true || isFlight == true) { //里面有关键字：航班，会议
		// isRemaind = true;
		// if(isFlight) {
		// keywords = "航班";
		// }
		// if(isMetting) {
		// keywords = "会议";
		// }
		// }
		return isRemaind;
	}
    
	/**识别文本中可被提醒的内容**/
	private void getRemindString(String content, String[] subStrings) {
		int[] array = new int[content.length()];
		for (int i = 0; i < array.length; i++) {
			array[i] = 10000;
		}

		for (int j = 0; j < subStrings.length; j++) {
			String findStr = subStrings[j];
			// 待查找字符串的长度
			int findLength = findStr.length();

			for (int i = 0; i < content.length();) {
				if ((findLength + i) <= content.length()
						&& content.substring(i, findLength + i).equals(findStr)) {
					// 查找到的位置
					System.out.println("find  " + i + "--"
							+ content.substring(i, findLength + i));
					array[i] = j;
					// 找到则下次查找的位置+字符长度
					i += findLength;
				} else {
					// 没有找到则从下一个位置开始查找
					i++;
				}
				if (i + findLength > content.length()) {
					// 如果下一次查找的endIndex>str.length()则说明不可能再有该字符串了
					break;
				}

			}
		}
		for (int i = 0; i < array.length; i++) {
			if (array[i] != 10000) {
				System.out.println("--" + subStrings[array[i]] + "--");
				isRemaind = true;
				keywordsList.add(subStrings[array[i]]);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			int backState = 0; // 记录back处理事件

			String strName = et_title_name.getText().toString(); // 文件名
			String strContent = et_content.getText().toString(); // 文件内容
			String color = String.valueOf(textColor); // 字体颜色

			Date date = new Date(System.currentTimeMillis()); // 系统当前时间
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			timeNow = dateFormat.format(date); // 保存时的时间
      
			String saveimgPath = tempStr; // 保存插入的图片
			int saveBackGroundId = savebgId; // 背景图片索引
            //TODO 
			StringBuffer savevideoPath = new StringBuffer();
			if(videoList.size()>0){
				for(int i=0;i<videoList.size();i++){
					savevideoPath.append(videoList.get(i));
				}
			}else{
				savevideoPath.append("");
			}
			
			String tempsaveBackGroundId = saveBackGroundId + "";
			// 如果整个界面的数据没有发生变，就不用进行数据库保存或者更新操作啦
			if (strName.equals(oldstrName) && strContent.equals(oldcontent)
					&& color.equals(oldcolor)
					&& saveimgPath.equals(oldimagePath)
					&& tempsaveBackGroundId.equals(oldbackground + "")
					&&savevideoPath.toString().equals(oldvideoPath)) {
				backState = BACK_NONE;
			} else if (strName.equals("") && strContent.equals("")&&savevideoPath.toString().equals("")&&
					saveimgPath.equals("")) {
				backState = BACK_NONE;
			} else {
				backState = BACK_SAVE;
			}

			if (backState == BACK_NONE) {//
				// 直接返回去
				Intent intent = new Intent(NewWriteActivity.this,
						WriteActivity.class);
				setResult(2); // 增加用户失败，不刷新主界面
				startActivity(intent);
				NewWriteActivity.this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			} else if (backState == BACK_SAVE) {
				// 弹出框
				openExitDialog();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/** 返回列表界面对话框 **/
	private void openExitDialog() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View viewDialog = inflater.inflate(R.layout.dialog_issave_remind, null);
		alertDlgExit = new AlertDialog.Builder(this).create();
		alertDlgExit.show();
		Display display = this.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		LayoutParams layoutParams = new LayoutParams(width * 90 / 100,
				LayoutParams.WRAP_CONTENT);
		alertDlgExit.setContentView(viewDialog, layoutParams);
		// alertDlgExit = new AlertDialog.Builder(this).create();
		// alertDlgExit.show();
		// Window window = alertDlgExit.getWindow();
		// window.setContentView(R.layout.newwrite_exit_dialog);
		Button sure_btn = (Button) viewDialog.findViewById(R.id.sure_btn);
		Button cancel_btn = (Button) viewDialog.findViewById(R.id.cancel_btn);
		sure_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 判断一下有没有内容（）
				saveorupdateWrite();
				alertDlgExit.dismiss();
			}
		});
		cancel_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgExit.dismiss();
				// 直接返回去
				Intent intent = new Intent(NewWriteActivity.this,
						WriteActivity.class);
				setResult(2); // 增加用户失败，不刷新主界面
				startActivity(intent);
				NewWriteActivity.this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			}
		});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.color_blue:
			// 更改颜色
			textColor = 0xFF0000FF;
			et_content.setTextColor(textColor);
			break;
		case R.id.color_green:
			// 更改颜色
			textColor = 0xFF06D700;
			et_content.setTextColor(textColor);
			break;
		case R.id.color_pink:
			// 更改颜色
			textColor = 0xFFFF3BD8;
			et_content.setTextColor(textColor);
			break;
		case R.id.color_red:
			// 更改颜色
			textColor = 0xFFFF0000;
			et_content.setTextColor(textColor);
			break;
		case R.id.color_purple:
			// 更改颜色
			textColor = 0xFF9931CD;
			et_content.setTextColor(textColor);
			break;
		case R.id.color_black:
			// 更改颜色
			textColor = 0xFF000000;
			et_content.setTextColor(textColor);
			break;
		//
		// case R.id.newwrite_et_content_image: //显示图片的imageView响应事件
		// //Toast.makeText(NewWriteActivity.this, "弹出放大框",
		// Toast.LENGTH_SHORT).show();
		// //打开对话框显示大图
		// loadBigPictureDialog(v);
		// break;

		default:
			break;
		}
		newwrite_ll_color.setVisibility(View.GONE);
	}

	/** 时间选择框的手动提醒监听器 **/
	public class MyTimePickerHandDialog implements
			TimePickerDialog.OnTimeSetListener {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			if (timeList.size() > 0) {
				if (timeList.size() > timerPosition
						&& timeList.get(timerPosition) != null) {
					timeList.remove(timerPosition);
				}
			}
			HashMap<String, Object> timeMap = new HashMap<String, Object>();
			timeMap.put("hour", hourOfDay);
			timeMap.put("minute", minute);
			timeList.add(timerPosition, timeMap);
			Calendar c = Calendar.getInstance();
			c.set(Calendar.HOUR_OF_DAY, hourOfDay);
			c.set(Calendar.MINUTE, minute);
			Date date = new Date(c.getTimeInMillis()); // 系统当前时间
			// Date date = new Date(System.currentTimeMillis());
			SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
			tv_remind_time.setText(dateFormat.format(date).toString());
		}

	}

	/** 时间选择框的监听器 **/
	public class MyTimePickerDialog implements
			TimePickerDialog.OnTimeSetListener {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// 此处可以获取到自己设置的时间
			// Toast.makeText(NewWriteActivity.this, hourOfDay +"---"+minute,
			// 1).show();

			isRSuccess = true;
			remaind = false;
			saveorupdateWrite(); // 调用一下保存到数据库
			// 将自己设置好的时间设置进去
			calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calendar.set(Calendar.MINUTE, minute);

			Intent intent = new Intent("com.mfnote.view");
			intent.setClass(NewWriteActivity.this, MyReceiver.class);

			// HashMap<String,Object> hashMap = new HashMap<String,Object>();
			// //hashMap
			// String strName = remindTitle;
			// String strContent = et_content.getText().toString(); // 文件内容
			// String color = String.valueOf(textColor); // 字体颜色
			// String time = timeNow;
			// String saveimgPath = tempStr; // 保存插入的图片
			// int saveBackGroundId = savebgId; // 背景图片索引
			// hashMap.put("title", strName);
			// hashMap.put("content", strContent);
			// hashMap.put("color", color);
			// hashMap.put("time", time);
			// hashMap.put("imagePath", saveimgPath);
			// hashMap.put("background", saveBackGroundId);
			// hashMap.put("lock", 0);
			// intent.putExtra("map", hashMap);
			// int requestCode = RandomUtils.getRequestCode();
			// intent.putExtra("requestCode", requestCode);
			PendingIntent pi = PendingIntent.getBroadcast(
					NewWriteActivity.this, 0, intent, 0);

			// 设置一个PendingIntent对象，发送广播
			AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
			// 获取AlarmManager对象
			am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi); // 时间到时，执行PendingIntent，只执行一次

			// AlarmManager.RTC_WAKEUP休眠时会运行，如果是AlarmManager.RTC,在休眠时不会运行
			// am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
			// 10000, pi);
			// 如果需要重复执行，使用上面一行的setRepeating方法，倒数第二参数为间隔时间,单位为毫秒

		}

	}

	/** 更多对话框 **/
	private void popupMoreWindow(View v) {
		// 加载
		LayoutInflater flater = getLayoutInflater();
		View contentView = flater.from(NewWriteActivity.this).inflate(
				R.layout.newwrite_item_popup_more, null);
		newwrite_more_ll_share = (LinearLayout) contentView
				.findViewById(R.id.newwrite_more_ll_share);
		newwrite_more_ll_bgselecter = (LinearLayout) contentView
				.findViewById(R.id.newwrite_more_ll_bgselector);
		newwrite_more_ll_accessory = (LinearLayout) contentView
				.findViewById(R.id.newwrite_more_ll_accessory);
		newwrite_more_ll_ciku = (LinearLayout) contentView
				.findViewById(R.id.newwrite_more_ll_ciku);
		newwrite_more_ll_video = (LinearLayout) contentView.findViewById(R.id.newwrite_more_ll_video);

		newwrite_more_ll_share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String strContent = et_content.getText().toString(); // 文件内容
				String saveimgPath = tempStr; // 保存插入的图片
				// String saveimgPath =
				// "/data/data/com.mfnote.view/files/IMG_20130620_151043.jpg";
				// //保存插入的图片
				boolean temp = new ImageManager(NewWriteActivity.this)
						.subImagePathString(saveimgPath);
				if (temp == true) { // 里面只有一张图片
					ShareUtil.share(saveimgPath, strContent,
							NewWriteActivity.this);
				} else {
					if(saveimgPath.equals("")&&strContent.equals("")){
						Toast.makeText(NewWriteActivity.this, "没有内容不能分享",
								Toast.LENGTH_SHORT).show();
					}
					else if (saveimgPath.equals("")) { // 没有图片，就只分享文字
						ShareUtil.share("", strContent, NewWriteActivity.this);
					} else {
						Toast.makeText(NewWriteActivity.this, "目前只能分享含有一张图片",
								Toast.LENGTH_SHORT).show();
					}
				}

				mPopupWindow.dismiss();
			}
		});
		newwrite_more_ll_bgselecter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 弹出背景选择对话框
				loadSelectBgDialog();
				mPopupWindow.dismiss();
			}
		});
		newwrite_more_ll_accessory.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 弹出图片选择对话框
				loadSelectPictureDialog();
			}
		});
		newwrite_more_ll_ciku.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 这里要进行手动提醒词库管理,弹出词库管理对话框
				loadRemainLexiconDialog();

			}
		});
		
		//调用系统的录制视频
		newwrite_more_ll_video.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO dc
				Intent mIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				mIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.5);// 画质0.5
				startActivityForResult(mIntent, CAMERA_TRANSCRIBE);
			}
		});

		if (mPopupWindow == null) {
			mPopupWindow = new PopupWindow(contentView,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			// 设置整个popupwindow的样式

			mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.more_popup_bg_5_item));
			// mPopupWindow.setAnimationStyle(R.style.AnimationPreview_right_buttom);

			// mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.newpaint_more_popup_bg2));
			// mPopupWindow.setAnimationStyle(R.style.AnimationPreview_right_buttom);

			mPopupWindow.setFocusable(true); // 使窗口里面的控件显示其相应的效果，比较点击button时背景颜色改变。
			mPopupWindow.update(); // 将给popupWindow设置的属性更新加载一下
		}
		if (!mPopupWindow.isShowing()) {
			// 显示出来
			mPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.RIGHT, 0,
					gv_buttom_menu.getHeight());
		}
	}

	/** 词库修改对话框 **/
	private void loadRemainLexiconDialog() {
		final Dialog builder = new Dialog(this, R.style.login_dialog_Dialog);
		builder.show();
		LayoutInflater inflater = LayoutInflater.from(this);
		View viewDialog = inflater
				.inflate(R.layout.dialog_remain_lexicon, null);
		Display display = this.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		// int height = display.getHeight();
		LayoutParams layoutParams = new LayoutParams(width * 90 / 100,
				LayoutParams.WRAP_CONTENT);
		builder.setContentView(viewDialog, layoutParams);

		final ListView lv = (ListView) viewDialog
				.findViewById(R.id.lv_remain_item);

		// 从数据库中获取数据
		final List<HashMap<String, Object>> list = remindDao.getAllReminds();
		// list.remove(0);

		final List<HashMap<String, Object>> listAll = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", list.get(i).get("name"));
			// 初始化是否被选中,默认都是未被选中
			map.put("checked", false);
			map.put("groupId", 0);
			listAll.add(map);
		}

		final SimpleAdapter adapter = new SimpleAdapter(this, listAll,
				R.layout.shortcut_item, new String[] { "name", "checked" },
				new int[] { R.id.tv_shortcut_text, R.id.cb_shortcut_check });
		lv.setAdapter(adapter);
		// lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				CheckBox cb_checked = (CheckBox) view
						.findViewById(R.id.cb_shortcut_check);
				boolean isChecked = (Boolean) listAll.get(position).get(
						"checked");
				String name = (String) listAll.get(position).get("name");
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put("name", name);
				if (position != 0) {
					if (isChecked) {
						hashMap.put("checked", false);
						cb_checked.setChecked(false);
					} else {
						hashMap.put("checked", true);
						cb_checked.setChecked(true);
					}
				} else {
					Toast.makeText(NewWriteActivity.this, "系统自带数据，不可删除！",
							Toast.LENGTH_SHORT).show();
					hashMap.put("checked", false);
					cb_checked.setChecked(false);
				}

				listAll.remove(position);
				listAll.add(position, hashMap);
			}

		});

		Button btn_delete = (Button) viewDialog.findViewById(R.id.delete_btn);
		Button btn_cancle = (Button) viewDialog.findViewById(R.id.cancel_btn);
		final Button btn_more = (Button) viewDialog.findViewById(R.id.more_btn);
		Button btn_add = (Button) viewDialog.findViewById(R.id.add_btn);
		final EditText et_name = (EditText) viewDialog
				.findViewById(R.id.word_et);
		final LinearLayout ll_more = (LinearLayout) viewDialog
				.findViewById(R.id.more_ll);
		final LinearLayout ll_add = (LinearLayout) viewDialog
				.findViewById(R.id.add_ll);

		btn_more.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ll_more.setVisibility(View.GONE);
				ll_add.setVisibility(View.VISIBLE);
			}
		});

		btn_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 获取editText中的值,添加到list中
				String name = et_name.getText().toString().trim();
				if (!"".equals(name) && name != null) {
					// 从集合中读取数据，判断word是否在该集合中，在则弹Toast提示已存在，否则执行添加

					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("name", name);
					map.put("checked", false);
					map.put("groupId", 0);
					if (listAll.contains(map)) {
						et_name.setText("");
						Toast.makeText(NewWriteActivity.this, "该数据已存在列表中",
								Toast.LENGTH_SHORT).show();
						return;
					}
					Log.d("name", "----" + et_name + "---");
					listAll.add(map);
					RemindEntity remindEntity = new RemindEntity(name, 0);
					remindDao.insertRemindEntity(remindEntity);
					et_name.setText("");
					ll_more.setVisibility(View.VISIBLE);
					ll_add.setVisibility(View.GONE);
				}

			}
		});

		btn_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// builder.dismiss();
				// 删除选中的item
				List<HashMap<String, Object>> deleteMap = new ArrayList<HashMap<String, Object>>();
				for (HashMap<String, Object> map : listAll) {
					boolean isChecked = (Boolean) map.get("checked");
					if (isChecked) {
						remindDao.deleteRemind(map);
						deleteMap.add(map);
					}
				}
				listAll.removeAll(deleteMap);

				listAll.clear();
				for (int i = 0; i <  remindDao.getAllReminds().size(); i++) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("name", remindDao.getAllReminds().get(i)
							.get("name"));
					// 初始化是否被选中,默认都是未被选中
					map.put("checked", false);
					map.put("groupId", 0);
					listAll.add(map);
				}
				adapter.notifyDataSetChanged();
				Toast.makeText(NewWriteActivity.this, "删除成功",
						Toast.LENGTH_SHORT).show();
			}
		});

		btn_cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				builder.dismiss();
				Toast.makeText(NewWriteActivity.this, "修改数据成功！",
						Toast.LENGTH_SHORT).show();
			}
		});

	}

	/******************************** 表情插入 ************************************************/

	private void initFace() {
		if (pageViews == null || pageViews.size() == 0 || pointViews == null
				|| pointViews.size() == 0) {
			initView(); // 初始化控件
			initViewPager(); // 初始化显示表情的ViewPager
			initPoint(); // 初始化游标
			initData(); // 填充数据
		}
	}

	/** 初始化控件 **/
	private void initView() {
		vp_face = (ViewPager) findViewById(R.id.vp_contains); // 显示表情页的viewpager
		layout_point = (LinearLayout) findViewById(R.id.iv_image); // 底部游标
		viewface = findViewById(R.id.ll_facechoose); // 包裹着整个表情选择框和底部小点图片的Rl布局
	}

	/** 初始化显示表情的viewPager **/
	private void initViewPager() {
		// 用于装载标签页的
		pageViews = new ArrayList<View>();
		// 左侧添加空页
		View nullView = new View(NewWriteActivity.this);
		// 设置透明背景
		nullView.setBackgroundColor(Color.TRANSPARENT);
		pageViews.add(nullView);

		// 中间添加表情页
		faceAdapters = new ArrayList<FaceAdapter>();
		for (int i = 0; i < emojis.size(); i++) {
			GridView gridView = new GridView(getApplicationContext());
			FaceAdapter adapter = new FaceAdapter(NewWriteActivity.this,
					emojis.get(i));
			gridView.setAdapter(adapter); // 给grideView装填适配器

			faceAdapters.add(adapter); // 将该适配器装进集合中

			gridView.setOnItemClickListener(this); // 绑定点击某一项的监听器
			// 给gridView设置属性值
			gridView.setNumColumns(7);
			gridView.setBackgroundColor(Color.TRANSPARENT);
			gridView.setHorizontalSpacing(1);
			gridView.setVerticalSpacing(1);
			gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
			gridView.setCacheColorHint(0);
			gridView.setPadding(5, 0, 5, 0);
			gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
			gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT));
			gridView.setGravity(Gravity.CENTER);

			pageViews.add(gridView); // 将已经装填好数据的view添加到集合中
		}

		// 右侧添加空白页
		View nullView2 = new View(NewWriteActivity.this);
		// 设置透明背景
		nullView2.setBackgroundColor(Color.TRANSPARENT);
		pageViews.add(nullView2);
	}

	/** 初始化游标 **/
	private void initPoint() {
		pointViews = new ArrayList<ImageView>();
		ImageView imageView;
		for (int i = 0; i < pageViews.size(); i++) {
			imageView = new ImageView(NewWriteActivity.this);
			// 设置布局属性
			imageView.setBackgroundResource(R.drawable.d1);
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT));
			layoutParams.leftMargin = 10;
			layoutParams.rightMargin = 10;
			layoutParams.width = 8;
			layoutParams.height = 8;

			layout_point.addView(imageView, layoutParams);
			if (i == 0 || i == pageViews.size() - 1) { // 第一个和最后一个空的View
				imageView.setVisibility(View.GONE);
			}
			if (i == 1) {
				imageView.setBackgroundResource(R.drawable.d2);
			}

			pointViews.add(imageView);
		}
	}

	/** 填充数据 **/
	private void initData() {
		// 将初始完成的pageViews
		vp_face.setAdapter(new ViewPageAdapter(pageViews));

		vp_face.setCurrentItem(1); // 设置当前默认页是第一页
		current = 0;
		vp_face.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				current = arg0 - 1;
				// 描绘分页点
				drawPoint(arg0);

				if (arg0 == pointViews.size() - 1 || arg0 == 0) {
					if (arg0 == 0) {
						vp_face.setCurrentItem(arg0 + 1);// 第二屏 会再次实现该回调方法实现跳转
						pointViews.get(1).setBackgroundResource(R.drawable.d2);
					} else {
						vp_face.setCurrentItem(arg0 - 1);// 倒数第二屏
						pointViews.get(arg0 - 1).setBackgroundResource(
								R.drawable.d2);
					}
				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	/** 表情选择监听 **/
	public interface OnCorpusSelectedListener {
		// 表情选择
		void onCorpusSelected(ChatEmoji emoji);

		// 表情删除
		void onCorpusDeleted();
	}

	/** 绘制游标背景 **/
	public void drawPoint(int index) {
		for (int i = 1; i < pointViews.size(); i++) {
			if (index == i) {
				pointViews.get(i).setBackgroundResource(R.drawable.d2);
			} else {
				pointViews.get(i).setBackgroundResource(R.drawable.d1);
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ChatEmoji emoji = (ChatEmoji) faceAdapters.get(current).getItem(
				position);
		// 删除图标
		if (emoji.getId() == R.drawable.face_del_icon) {
			int selection = et_content.getSelectionStart();
			String text = et_content.getText().toString();
			// 前面有内容
			if (selection > 0) {
				String text2 = text.substring(selection - 1); // 获取最后一个字符 ]
				if ("]".equals(text2)) {
					int start = text.lastIndexOf("[");
					int end = selection;
					et_content.getText().delete(start, end); // 删除编辑框中的内容
					return;
				}
				et_content.getText().delete(selection - 1, selection);
			}
		}
		// 其他图标
		if (!TextUtils.isEmpty(emoji.getCharacter())) {
			if (mListener != null)
				// 表情被选择了
				mListener.onCorpusSelected(emoji);
			// 添加表情
			SpannableString spannableString = FaceConversionUtil.getInstance()
					.addFace(NewWriteActivity.this, emoji.getId(),
							emoji.getCharacter());
			Editable editable = et_content.getEditableText();
			int selectedIndex = et_content.getSelectionStart(); // 获取光标位置

			if (selectedIndex < 0)
				editable.append(spannableString);
			else
				editable.insert(selectedIndex, spannableString);
			// 隐藏表情选择框
			if (viewface_include.getVisibility() == View.VISIBLE) {
				viewface_include.setVisibility(View.GONE);
			}
		}
	}

}
